using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace LibraryManagementSystem
{
    public partial class BookItemsForm : Form
    {
        private readonly BookService _bookService;
        private readonly Book _book;
        private List<BookItem> _bookItems;

        public BookItemsForm(Book book)
        {
            InitializeComponent();
            _bookService = new BookService();
            _book = book;
            this.Text = $"管理副本 - {book.Title}";
        }

        private void BookItemsForm_Load(object sender, EventArgs e)
        {
            // 加载图书信息
            lblBookInfo.Text = $"《{_book.Title}》 作者：{_book.Author} ISBN：{_book.ISBN}";
            
            // 初始化状态下拉框
            cmbStatus.Items.Clear();
            cmbStatus.Items.Add("在馆");
            cmbStatus.Items.Add("借出");
            cmbStatus.Items.Add("预约");
            cmbStatus.Items.Add("维修");
            cmbStatus.Items.Add("丢失");
            cmbStatus.SelectedIndex = 0;

            // 设置日期默认值为今天
            dtpAcquisitionDate.Value = DateTime.Now;
            
            // 加载图书副本
            LoadBookItems();
        }

        private void LoadBookItems()
        {
            try
            {
                _bookItems = _bookService.GetBookItems(_book.Id);
                
                lvBookItems.Items.Clear();
                foreach (var item in _bookItems)
                {
                    var listItem = new ListViewItem(item.BarCode);
                    listItem.SubItems.Add(item.Status);
                    listItem.SubItems.Add(item.AcquisitionDate.ToString("yyyy-MM-dd"));
                    listItem.SubItems.Add(item.LastBorrowDate?.ToString("yyyy-MM-dd HH:mm") ?? "从未借出");
                    listItem.SubItems.Add(item.Notes ?? "");
                    listItem.Tag = item;
                    
                    // 根据状态设置不同颜色
                    switch (item.Status)
                    {
                        case "在馆":
                            listItem.BackColor = System.Drawing.Color.LightGreen;
                            break;
                        case "借出":
                            listItem.BackColor = System.Drawing.Color.LightPink;
                            break;
                        case "预约":
                            listItem.BackColor = System.Drawing.Color.LightYellow;
                            break;
                        case "维修":
                            listItem.BackColor = System.Drawing.Color.LightGray;
                            break;
                        case "丢失":
                            listItem.BackColor = System.Drawing.Color.LightCoral;
                            break;
                    }
                    
                    lvBookItems.Items.Add(listItem);
                }
                
                lblTotalItems.Text = $"总共 {_bookItems.Count} 个副本 | 在馆: {_bookItems.Count(i => i.Status == "在馆")} | 借出: {_bookItems.Count(i => i.Status == "借出")} | 预约: {_bookItems.Count(i => i.Status == "预约")} | 维修: {_bookItems.Count(i => i.Status == "维修")} | 丢失: {_bookItems.Count(i => i.Status == "丢失")}";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载副本数据时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddItem_Click(object sender, EventArgs e)
        {
            // 验证输入
            if (string.IsNullOrEmpty(txtBarCode.Text))
            {
                MessageBox.Show("请输入条形码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            
            // 检查条形码是否已存在
            bool barcodeExists = _bookItems.Exists(i => i.BarCode == txtBarCode.Text.Trim());
            if (barcodeExists)
            {
                MessageBox.Show("此条形码已存在", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            
            // 创建副本对象
            var bookItem = new BookItem
            {
                BookId = _book.Id,
                BarCode = txtBarCode.Text.Trim(),
                Status = cmbStatus.SelectedItem.ToString(),
                AcquisitionDate = dtpAcquisitionDate.Value,
                Notes = txtNotes.Text.Trim()
            };
            
            // 保存副本
            int id = _bookService.AddBookItem(bookItem);
            
            if (id > 0)
            {
                MessageBox.Show("副本添加成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                ClearForm();
                LoadBookItems();
            }
            else
            {
                MessageBox.Show("添加副本失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnUpdateStatus_Click(object sender, EventArgs e)
        {
            if (lvBookItems.SelectedItems.Count == 0)
            {
                MessageBox.Show("请选择要更新的副本", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            
            var selectedItem = lvBookItems.SelectedItems[0].Tag as BookItem;
            string newStatus = cmbStatus.SelectedItem.ToString();
            
            bool success = _bookService.UpdateBookItemStatus(selectedItem.Id, newStatus);
            
            if (success)
            {
                MessageBox.Show("状态更新成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                LoadBookItems();
            }
            else
            {
                MessageBox.Show("更新状态失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnDeleteItem_Click(object sender, EventArgs e)
        {
            if (lvBookItems.SelectedItems.Count == 0)
            {
                MessageBox.Show("请选择要删除的副本", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            
            var selectedItem = lvBookItems.SelectedItems[0].Tag as BookItem;
            
            var result = MessageBox.Show($"确定要删除条形码为 {selectedItem.BarCode} 的副本吗？", "确认删除", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            
            if (result == DialogResult.Yes)
            {
                bool success = _bookService.DeleteBookItem(selectedItem.Id);
                
                if (success)
                {
                    MessageBox.Show("副本删除成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ClearForm();
                    LoadBookItems();
                }
                else
                {
                    MessageBox.Show("无法删除副本，可能该副本当前已被借出", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void lvBookItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvBookItems.SelectedItems.Count > 0)
            {
                var selectedItem = lvBookItems.SelectedItems[0].Tag as BookItem;
                
                txtBarCode.Text = selectedItem.BarCode;
                cmbStatus.SelectedItem = selectedItem.Status;
                dtpAcquisitionDate.Value = selectedItem.AcquisitionDate;
                txtNotes.Text = selectedItem.Notes;
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            ClearForm();
        }

        private void ClearForm()
        {
            txtBarCode.Text = string.Empty;
            cmbStatus.SelectedIndex = 0;
            dtpAcquisitionDate.Value = DateTime.Now;
            txtNotes.Text = string.Empty;
            lvBookItems.SelectedItems.Clear();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
} 